<?php
/**
 * @Author: hpp
 * @Date:   2018-11-08 10:25:07
 * @Last Modified by:   hpp
 * @Last Modified time: 2018-11-12 12:33:55
 */
namespace app\http\middleware;

use app\admin\model\AdminRole;
use app\admin\model\PermissionRole;
use app\admin\model\Permission;

class Check
{
    use \traits\controller\Jump;
    public function handle($request, \Closure $next)
    {
        $user = session('user');
        if(!$user){
            return redirect('/admin/login');
        }
        $controller = $request->controller();
        $action = $request->action();
        // 查询当前管理员的角色
        $roleId = AdminRole::where('admin_id',$user['id'])->value('role_id');
        // 查询当前角色的权限
        $permissionId = PermissionRole::where('role_id',$roleId)->value('permission_id');
        $permission = Permission::where('id','in',$permissionId)->column('route');
        $currentRoute = strtolower($controller.'/'.$action);
        $permission = array_map(function($val){
            return strtolower($val);
        },$permission);
        if(!in_array($currentRoute,$permission)){
            if($request->isAjax()){
                return json(['code' => 0,'msg' => '没有权限，请联系管理员']);
            }else{
                // TODO 跳转操作
                $this->error('没有权限，请联系管理员');
            }
        }
    	return $next($request);
    }
}
